package org.eenie.cartoonist.provider;


import org.eenie.cartoonist.base.BaseApp;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by Eenie on 2016/8/15.
 * 提供一个请求网络的客户端单例
 */

public class OkHttpProvider {
    private static OkHttpClient mInstance;
    private static final long TIME_OUT = 10;
    private static final int default_cache_size = 50 * 1024 * 1024;
    private static final String cache_path = "netCache";

    public static OkHttpClient get() {
        if (mInstance == null) {
            synchronized (OkHttpProvider.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpClient().newBuilder()
                            .addInterceptor(new HttpLoggingInterceptor())
                            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .retryOnConnectionFailure(true)//连接失败后重试
//                            .addInterceptor(new CacheInterceptor())//缓存管理
                            .cache(fetCache())
                            .build();
                }
            }
        }
        return mInstance;
    }

    public static Cache fetCache() {
        File file = new File(BaseApp.appContext().getExternalCacheDir() + File.separator + cache_path);
        Cache cache = new Cache(file, default_cache_size);
        return cache;
    }
}
